package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        // 解决缓存穿透问题
//        Shop shop = queryWithPassThrough(id);

//        Shop shop = queryWithMutex(id);
//        if (shop == null) {
//            return Result.fail("店铺信息不存在");
//        }
//        Shop shop = queryWithLogicalExpire(id);
        Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES, LOCK_SHOP_KEY);
        return Result.ok(shop);
    }

    // 利用互斥锁解决缓存击穿问题
    private Shop queryWithMutex(Long id) {
        // 1.查询缓存，判断有没有缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        log.info("shopJson:{}", shopJson);
        if (StrUtil.isNotBlank(shopJson)) {
            // 2.如果有，返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        // 这里就是空数据
        if (shopJson != null) {
            return null;
        }
        Shop shop = null;

        try {
            // 实现缓存重建
            // 3.1 尝试获取锁
            boolean lock = tryLock(LOCK_SHOP_KEY + id);

            // 3.3 没有获取到锁，自旋等待获取锁
            while (!lock) {
                lock = tryLock(LOCK_SHOP_KEY + id);
                Thread.sleep(50);
            }
            // 3.2 获取到锁，查询数据库,这里应该再次查询redis，进行double check，如果有就不用进行数据库的查询了
            String doubleCheck = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
            if (StrUtil.isNotBlank(doubleCheck)) {
                // 如果有，返回
                return JSONUtil.toBean(doubleCheck, Shop.class);
            }

            // 4.如果没有，用数据库查询，然后存入redis
            shop = getById(id);
            if (shop == null) {
                // 空数据，同样存储到redis
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 最后释放锁
            unlock(LOCK_SHOP_KEY + id);
        }

        return shop;
    }

    private final static ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    private Shop queryWithLogicalExpire(Long id) {
        // 1.查询缓存，判断有没有缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if (StrUtil.isBlank(shopJson)) {
            // 2.如果没有，返回
            // TODO 这里其实是有点问题的，如果缓存中没有，那么应该去数据库查询，而不是直接返回空值，应该是为了redis不考虑其他的
            return null;
        }
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        // 判断缓存是否过期
        if (LocalDateTime.now().isBefore(expireTime)){
            // 未过期，直接返回
            return shop;
        }
        try {
            // 过期了，进行缓存重建
            Boolean lock = tryLock(LOCK_SHOP_KEY + id);
            // 获取到锁了，开启新的线程，进行操作
            // 获取到锁也要进行双重检测，如果线程1还正在判断缓存是否过期，判断为过期了，线程2此时在重建缓存，那么等到线程2操作完，线程1还会重建一次缓存，这样就会导致一直重建缓存
            if(lock){
                String shopJsonDouble = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
                RedisData redisDataDouble = JSONUtil.toBean(shopJsonDouble, RedisData.class);
                LocalDateTime expireTimeDouble = redisData.getExpireTime();
                JSONObject dataDouble = (JSONObject) redisData.getData();
                Shop shopDouble = JSONUtil.toBean(data, Shop.class);
                // 判断缓存是否过期
                if (LocalDateTime.now().isBefore(expireTimeDouble)){
                    // 未过期，直接返回
                    return shopDouble;
                }
                CACHE_REBUILD_EXECUTOR.submit(() ->{
                    this.saveShop2Redis(id,30L);
                });
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            unlock(LOCK_SHOP_KEY + id);
        }
        return shop;
    }

    public void saveShop2Redis(Long id, Long expireTime) {
        RedisData redisData = new RedisData();
        Shop shop = getById(id);
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    // 解决缓存穿透问题
    private Shop queryWithPassThrough(Long id) {
        // 1.查询缓存，判断有没有缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if (StrUtil.isNotBlank(shopJson)) {
            // 2.如果有，返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        // 这里就是空数据
        if (shopJson != null) {
            return null;
        }

        // 3.如果没有，用数据库查询，然后存入redis
        Shop shop = getById(id);
        if (shop == null) {
            // 空数据，同样存储到redis
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop));
        stringRedisTemplate.expire(CACHE_SHOP_KEY + id, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }

    private Boolean tryLock(String key) {
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(b);
    }

    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺信息不能为空");
        }
        // 更新数据库
        updateById(shop);
        // 删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }
}
